//
//  QCComposeViewController.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/8.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit

class QCComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //MARK: - 设置视图
    private func setupUI() {
       
      view.backgroundColor = UIColor.groupTableViewBackground
        setupNav()
        
        view.addSubview(composeTextView)
        composeTextView.addSubview(composePictureView)
        view.addSubview(composeBottomView)
        
        composeTextView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        composePictureView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: KSCREENW-20, height: KSCREENW-20))
            make.top.equalToSuperview().offset(100)
            make.centerX.equalToSuperview()
        }
        
        composeBottomView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(40)
        }
        
        //闭包
        composeBottomView.closure = {[weak self] (type)->() in
            
            switch type {
            case .picture:
                print("图片")
                self?.selectImage()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("笑脸")
                self?.changeKeyboard()
            case .add:
                print("+")
            }
        }
        
        composePictureView.closure = { [weak self] ()->() in
            
          self?.selectImage()
            
        }
        
        //监听键盘将要改变frame的通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonNoti), name: NSNotification.Name(rawValue:EMOTIONBUTTONNOTI), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonDeleteButtonNoti), name: NSNotification.Name(rawValue:EMOTIONDELETEBUTTONNOTI), object: nil)
        
    }
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "发送", target: self, action: #selector(sendAction))
        self.navigationItem.rightBarButtonItem?.isEnabled = false
       navigationItem.titleView = titleView
    }
    
    //懒加载控件
    private lazy var titleView: UILabel = {
       //获取微博用户的昵称
        let name = QCOAuthViewModel.shared.userAccountModel?.screen_name ?? ""
        //设置发布微博最终显示的内容
        let str = "发微博\n\(name)"
        //获取范围
        let range = (str as NSString).range(of: name)
        
        //可变富文本
        let attr = NSMutableAttributedString(string: str)
        //设置
        attr.addAttributes([NSForegroundColorAttributeName:KCOlOR,NSFontAttributeName:UIFont.systemFont(ofSize: 12)], range: range)
        
        let lab = UILabel()
        
        lab.attributedText = attr
        
        lab.numberOfLines = 0
        
        lab.textAlignment = .center
        
        lab.sizeToFit()
        
        return lab
        
    }()
    
    fileprivate lazy var composeTextView:QCComposeTextView = {
       
        let view = QCComposeTextView()
        view.placeholder = "耍手机按时间段爱上的空间和爱上的厉害 爱上的老客户j"
        view.font = UIFont.systemFont(ofSize: QCNORMALFONTSIZE)
        
        view.delegate = self
        
        view.alwaysBounceVertical = true
        
        return view
    }()
    
    fileprivate lazy var composeBottomView:QCComposeBottomView = QCComposeBottomView()
    fileprivate lazy var composePictureView:QCComposePictureView = QCComposePictureView()
    fileprivate lazy var emotionKeyboardView:QCEmotionKeyboardView = QCEmotionKeyboardView()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}


extension QCComposeViewController {
    //从相片中获取图片
    func selectImage() {
        let  pickerVC = UIImagePickerController()
        
        pickerVC.delegate = self
        
        self.present(pickerVC, animated: true, completion: nil)
    }
    
    func changeKeyboard(){
        
        if self.composeTextView.inputView == nil {
            self.composeTextView.inputView = self.emotionKeyboardView
            self.composeBottomView.isEmoticon = true
        }else {
            self.composeTextView.inputView = nil
            self.composeBottomView.isEmoticon = false
        }
        //成为第一响应者
        self.composeTextView.becomeFirstResponder()
        //刷新
        self.composeTextView.reloadInputViews()
    }
    
}

extension QCComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        self.composePictureView.addImage(image: image.dealImageScale(width: 400))
                                                                                                                                                                                                                                                                                                                         }
    
}

// 监听键盘通知
extension QCComposeViewController {
    
    func emoticonButtonNoti(noti:Notification){
     
        
        
    }
    
    func emoticonDeleteButtonNoti(){
        self.composeTextView.deleteBackward()
    }
    
    func keyboardWillChangeFrame(noti:Notification){
        
        guard let userInfo = noti.userInfo as?[String:Any] else{
            return
        }
        //键盘的frame
        let frame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        //动画时间
        let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //改变底部视图的位置
        self.composeBottomView.snp.updateConstraints { (make) in
            make.bottom.equalToSuperview().offset(frame.origin.y - KSCREENH)
        }
        //更新约束
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
}

//代理 监听textView 发生改变
extension QCComposeViewController: UITextViewDelegate {
 
    
    func textViewDidChange(_ textView: UITextView) {
        self.navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.composeTextView.resignFirstResponder()
    }
    
}

extension QCComposeViewController {
    
    @objc fileprivate func cancelAction(){
        dismiss(animated: true, completion: nil)
    }
    @objc fileprivate func sendAction(){
        if self.composePictureView.images.count > 0 {
           upload()
        }else {
            update()
        }
    }
}

//发布微博
extension QCComposeViewController {
    func update(){
       
      QCNetworkTools.shared.update(status: self.composeTextView.text, success: { (res) in
        print("发送成功")
      },failure: { (err) in
      print("发送失败",err)
        
    })
}
    func upload(){
        QCNetworkTools.shared.upload(status: self.composeTextView.text, images: self.composePictureView.images, success: { (res) in
            print("成功")
        },failure: { (err) in
            print("失败",err)
        })
    }
}
